package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.manager.feign.ChartCategoryFeignClient;
import com.xbongbong.paas.pojo.ChartCategoryDTO;
import com.xbongbong.paas.pojo.IdNamePojo;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.PerformanceSetService;
import com.xbongbong.paas.service.PkSetService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigEnableDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigSetFiscalDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigSetWorkingDayMonthDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigSetWorkingDayWeekDTO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PerformanceErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.global.ChartCategoryEnum;
import com.xbongbong.pro.enums.menu.enums.OtherSetEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.performanceset.pojo.PerformanceChartLogOrderPojo;
import com.xbongbong.pro.performanceset.pojo.PerformanceSetExplainPojo;
import com.xbongbong.pro.performanceset.pojo.PerformanceSetInitPojo;
import com.xbongbong.pro.performanceset.pojo.PerformanceSetListPojo;
import com.xbongbong.pro.performanceset.pojo.PerformanceSetProductPojo;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetCheckDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetDeleteDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetDetailDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetEditDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetEnableDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetInitDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetListByPermissionDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetListDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetPermissionListDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetProductListDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetSaveDTO;
import com.xbongbong.pro.performanceset.pojo.dto.PerformanceSetSaveGuideDTO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetCheckVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetDeleteVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetDetailVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetEditVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetEnableVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetInitVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetListByPermissionVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetListVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetPermissionListVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetSaveGuideVO;
import com.xbongbong.pro.performanceset.pojo.vo.PerformanceSetSaveVO;
import com.xbongbong.pro.service.toolbox.statistic.help.PerformanceHelp;
import com.xbongbong.pro.statistic.enums.ChartCategoryTypeEnum;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.pro.statistic.pojo.dto.ChartCategorySaveDTO;
import com.xbongbong.pro.statistic.pojo.vo.ChartCategorySaveVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.AssessTypeEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.MinCycleEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.service.toolbox.statistic.help.ChartHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.CompanyStructTypeEnum;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @description: 业绩目标指标
 * @Author: hongxiao
 * @date: 2019-01-25 14:39
 */
@Service("performanceSetService")
public class PerformanceSetServiceImpl implements PerformanceSetService {
    private static final Logger LOG = LoggerFactory.getLogger(PerformanceSetServiceImpl.class);

    @Resource
    private ChartModel chartModel;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private PerformanceHelp performanceHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private ChartHelp chartHelp;
    @Resource
    private PkSetService pkSetService;
    @Resource
    private ChartCategoryFeignClient chartCategoryFeignClient;
    @Resource
    private LogHelp logHelp;

    @Override
    public PerformanceSetInitVO init(PerformanceSetInitDTO performanceSetInitDTO) throws XbbException {
        PerformanceSetInitVO initVO = new PerformanceSetInitVO();

        String corpid = performanceSetInitDTO.getCorpid();
        Integer chartType = ChartTypeEnum.PERFORMANCE.getCode();

        try {
            List<ChartEntity> list = chartModel.getList(corpid, null, chartType);
            if (list == null || list.size() == 0) {
                // 枚举,获取指标分类表中的业绩目标
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("alias", "performance");
                param.put("del", DelEnum.NORMAL.getDel());
                List<ChartCategoryEntity> categoryEntityList = chartCategoryModel.findEntitys(param);
                if (categoryEntityList == null || categoryEntityList.size() == 0) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "业绩目标不存在");
                }
                Long categoryId = categoryEntityList.get(0).getId();

                list = getDefaultSystemList(chartType);
                // 考核周期，考核方式，考核值
                PerformanceSetExplainPojo explains = new PerformanceSetExplainPojo();
                String explainsStr = JSON.toJSONString(explains);
                JSONObject explainObj = JsonHelperUtil.parseObject(explainsStr);
                long now = DateUtil.getInt();
                for (ChartEntity entity : list) {
                    entity.setId(null);
                    entity.setCorpid(corpid);
                    entity.setExplains(explainObj);
                    entity.setUpdateTime(now);
                    entity.setAddTime(now);
                    entity.setCategoryId2Category(categoryId);
                }
                chartModel.insertBatch(list);
            }
            List<PerformanceSetInitPojo> resultList = new ArrayList<>();
            BeanUtil.copyPropertiesList(list, resultList, PerformanceSetInitPojo.class);

            initVO.setList(resultList);

        } catch (Exception e) {
            LOG.error("获取业绩目标指标失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return initVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PerformanceSetSaveGuideVO saveGuide(PerformanceSetSaveGuideDTO saveGuideDTO) throws XbbException {
        PerformanceSetSaveGuideVO saveGuideVO = new PerformanceSetSaveGuideVO();

        String corpid = saveGuideDTO.getCorpid();
        Integer chartType = ChartTypeEnum.PERFORMANCE.getCode();
        List<Long> idIn = saveGuideDTO.getIdIn();
        List<IdNamePojo> permissions = saveGuideDTO.getPermissions();

        List<ChartEntity> list;
        try {
            list = chartModel.getList(corpid, null, chartType);
        } catch (Exception e) {
            LOG.error("获取业绩目标指标失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 要关闭的指标
        List<ChartEntity> closeEntitys = new ArrayList<>();
        boolean flag = true;
        long now = DateUtil.getInt();
        StringBuffer memo = new StringBuffer();
        for (ChartEntity entity : list) {
            Long id = entity.getId();
            if (idIn.contains(id)) {
                JSONObject performanceObj = setPerSetPermission(permissions);
                flag = false;
                entity.setEnable(BasicConstant.IS_USE);
                entity.setUpdateTime(now);
                entity.setPermissions(performanceObj);
                try {
                    chartModel.update(entity);
                } catch (Exception e) {
                    LOG.error("保存业绩目标指标失败", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }

                if (memo.length() > 0) {
                    memo.append("、");
                }
                memo.append("“" + entity.getName() + "”");

            } else {
                // 默认启用的又不启用
                entity.setEnable(BasicConstant.NO_USE);
                entity.setUpdateTime(now);
                // 这个要在判断过是否至少启用了一个指标以后才能进行更新入库
                closeEntitys.add(entity);
            }
        }
        if (flag) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "请返回第一步");
        }
        for (ChartEntity entity : closeEntitys) {
            try {
                chartModel.update(entity);
            } catch (Exception e) {
                LOG.error("保存业绩目标指标失败", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
        }

        // 财年
        CompanyConfigSetFiscalDTO setFiscalDTO = new CompanyConfigSetFiscalDTO();
        setFiscalDTO.setCorpid(corpid);
        setFiscalDTO.setStartMonth(saveGuideDTO.getStartMonth());
        companyConfigService.setFiscal(setFiscalDTO);

        // 月工作日
        CompanyConfigSetWorkingDayMonthDTO workingDayMonthDTO = new CompanyConfigSetWorkingDayMonthDTO();
        workingDayMonthDTO.setWorkingDayMonth(saveGuideDTO.getWorkingDayMonth());
        workingDayMonthDTO.setCorpid(corpid);
        companyConfigService.setWorkingDayMonth(workingDayMonthDTO);

        // 周工作日
        CompanyConfigSetWorkingDayWeekDTO workingDayWeekDTO = new CompanyConfigSetWorkingDayWeekDTO();
        workingDayWeekDTO.setWorkingDayWeek(saveGuideDTO.getWorkingDayWeek());
        workingDayWeekDTO.setCorpid(corpid);
        companyConfigService.setWorkingDayWeek(workingDayWeekDTO);

        // 允许员工在移动端设置个人目标
        CompanyConfigEnableDTO enableDTO = new CompanyConfigEnableDTO();
        enableDTO.setCorpid(corpid);
        enableDTO.setAlias(CompanyConfigEnum.PERFORMANCE_SET.getAlias());
        enableDTO.setValue(saveGuideDTO.getEnablePerformance().toString());
        companyConfigService.enable(enableDTO);

        // 允许主管及以上角色在移动端设置目标
        enableDTO.setAlias(CompanyConfigEnum.PERFORMANCE_MANAGE_SET.getAlias());
        enableDTO.setValue(saveGuideDTO.getEnablePerformanceManage().toString());
        companyConfigService.enable(enableDTO);

        // 业绩目标是否显示离职员工
        enableDTO.setAlias(CompanyConfigEnum.PERFORMANCE_LEAVE.getAlias());
        enableDTO.setValue(saveGuideDTO.getEnablePerformanceLeave().toString());
        companyConfigService.enable(enableDTO);

        // 日志
        String opUserName = saveGuideDTO.getLoginUserName();
        String opObjectId = "";
        String opMemo = opUserName + "初始化了业绩目标模块的指标，启用了指标：" + memo;
        mongoLogHelp.buildLog(corpid, saveGuideDTO.getUserId(), opUserName, OperateModuleTypeEnum.PerformanceObject, OperateTypeEnum.ENABLE, opObjectId, OtherSetEnum.GOAL_MANAGEMENT.getName(), opMemo, saveGuideDTO.getHttpHeader());
        return saveGuideVO;
    }

    @Override
    public PerformanceSetListVO list(PerformanceSetListDTO performanceSetListDTO) throws XbbException {
        PerformanceSetListVO listVO = new PerformanceSetListVO();

        String corpid = performanceSetListDTO.getCorpid();
        Integer chartType = ChartTypeEnum.PERFORMANCE.getCode();
        List<ChartEntity> list;
        try {
            list = chartModel.getList(corpid, null, chartType);
        } catch (Exception e) {
            LOG.error("获取业绩目标指标失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        if (list.size() > 0) {
            List<PerformanceSetListPojo> enableList = new ArrayList<>();
            List<PerformanceSetListPojo> disableList = new ArrayList<>();
            for (ChartEntity entity : list) {
                PerformanceSetExplainPojo explainPojo = performanceHelp.getPerformanceSetExplainPojo(entity);

                List<IdNamePojo> permissionList = performanceHelp.getPermissionList(entity);
                String depNames = performanceHelp.getPermissions2DepNames(permissionList);

                // 名称包含旧名字
                StringBuffer nameBuffer = new StringBuffer();
                nameBuffer.append(entity.getName());
                if(!Objects.equals(entity.getName(), entity.getOldName())) {
                    nameBuffer.append("(原名：").append(entity.getOldName()).append(")");
                }


                PerformanceSetListPojo pojo = new PerformanceSetListPojo();
                BeanUtil.copyProperties(entity, pojo);
                pojo.setName(nameBuffer.toString());
                pojo.setDepNames(depNames);
                pojo.setAssessType(explainPojo.getAssessType());
                pojo.setMinCycle(explainPojo.getMinCycle());

                boolean isUse = entity.getEnable() != null && entity.getEnable().equals(BasicConstant.IS_USE);
                if (isUse) {
                    enableList.add(pojo);
                } else {
                    disableList.add(pojo);
                }
            }
            listVO.setEnableList(enableList);
            listVO.setDisableList(disableList);
        }

        return listVO;
    }

    @Override
    public PerformanceSetDetailVO detail(PerformanceSetDetailDTO performanceSetDetailDTO) throws XbbException {
        PerformanceSetDetailVO detailVO = new PerformanceSetDetailVO();
        String corpid = performanceSetDetailDTO.getCorpid();
        String userId = performanceSetDetailDTO.getUserId();
        Long id = performanceSetDetailDTO.getId();
        Integer statisticsType = performanceSetDetailDTO.getStatisticsType();
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }

        // 获取目标实体
        ChartEntity entity = performanceHelp.getSetEntity(statisticsType,corpid,id);

        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getByCode(statisticsType);
        String statisticsTypeStr = statisticsTypeEnum.getName();

        List<IdNamePojo> permissionList = performanceHelp.getPermissionList(entity);
        String depNames = performanceHelp.getPermissions2DepNames(permissionList);

        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 超管角色查看所有
        boolean containsFlag = true;
        // 获取操作人权限
        if (!DataPermissionEnum.ALL.getCode().equals(dataPermission)) {
            // 非超管，判断是否在考核对象内
            containsFlag = performanceHelp.checkViewPerformanceSetByUserId(corpid, userId, permissionList, id);
        }
        PerformanceSetExplainPojo explainPojo = performanceHelp.getPerformanceSetExplainPojo(entity);

        MinCycleEnum minCycleEnum = MinCycleEnum.getByCode(explainPojo.getMinCycle());
        String minCycleStr = "";
        if (minCycleEnum != null) {
            minCycleStr = minCycleEnum.getName();
        }

        Integer refType = XbbRefTypeEnum.UNKNOWN.getCode();
        if (entity.getRefTypes() != null) {
            List<Integer> refTypes = JsonHelperUtil.parseArray(entity.getRefTypes(), Integer.class);
            if (refTypes != null && refTypes.size() > 0) {
                refType = refTypes.get(0);
            }
        }
        /*
         * 涉及到产品目标考核的时候允许选择考核的产品（多选）
         */
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(refType);
        boolean productFlag = xbbRefTypeEnum == XbbRefTypeEnum.PRODUCT;
        List<Long> assessProductList = explainPojo.getAccessProductIds();
        // 考核产品，且选择了考核哪些产品
        List<PerformanceSetProductPojo> assessProductArray = getAssessProductArray(corpid, productFlag, assessProductList);

        // 名称包含旧名字
        StringBuffer nameBuffer = new StringBuffer();
        nameBuffer.append(entity.getName());
        if(!Objects.equals(entity.getName(), entity.getOldName())) {
            nameBuffer.append("(原名：").append(entity.getOldName()).append(")");
        }

        detailVO.setId(id);
        detailVO.setStatisticsType(statisticsType);
        detailVO.setStatisticsTypeStr(statisticsTypeStr);
        detailVO.setName(nameBuffer.toString());
        detailVO.setMemo(entity.getMemo());
        detailVO.setDepNames(depNames);
        detailVO.setMinCycleStr(minCycleStr);
        detailVO.setAssessType(explainPojo.getAssessType());
        detailVO.setUnit(entity.getOriginalUnit());
        detailVO.setFixedValue(explainPojo.getFixedValue());

        detailVO.setProductFlag(productFlag);
        detailVO.setAssessProductArray(assessProductArray);
        detailVO.setContainsFlag(containsFlag);
        // 导入权限
        Set<String> perAlias = performanceSetDetailDTO.getLoginUser().getPermSet();
        detailVO.setImportFlag(perAlias.contains(ProPermissionAliasEnum.OBJECTIVE_IMPORT.getAlias()));

        return detailVO;
    }

    @Override
    public PerformanceSetEditVO edit(PerformanceSetEditDTO performanceSetEditDTO) throws XbbException {
        PerformanceSetEditVO editVO = new PerformanceSetEditVO();
        String corpid = performanceSetEditDTO.getCorpid();
        Long id = performanceSetEditDTO.getId();
        String userId = performanceSetEditDTO.getUserId();
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        Integer statisticsType= performanceSetEditDTO.getStatisticsType();

        ChartEntity entity = new ChartEntity();
        List<IdNamePojo> permissionList = new ArrayList<>();
        Integer minCycle;
        JSONArray minCycleArray = MinCycleEnum.getMinCycleArray();
        Integer assessType;
        Double fixedValue = null;
        List<PerformanceSetProductPojo> assessProductArray = null;
        Boolean productFlag = null;
        JSONObject  driverSources = new JSONObject();
        JSONObject sourceAttr = new JSONObject();
        JSONObject belongAttr = new JSONObject();
        JSONObject timeAttr = new JSONObject();
        JSONArray filter = new JSONArray();
        JSONArray penetrateAttr = new JSONArray();

        if (null == id){
            if (!StatisticsTypeEnum.getStatisticTypes().contains(statisticsType)){
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240030,PerformanceErrorCodeEnum.API_ERROR_240030.getMsg());
            }
            IdNamePojo pojo = new IdNamePojo();
            pojo.setId(PaasConstant.CORP_DEPARTMENT_ID);
            pojo.setName(I18nMessageUtil.getMessage(CommonConstant.COMPANY_WIDE));
            permissionList.add(pojo);
            minCycle = BasicConstant.ONE;
            assessType = BasicConstant.ONE;
        }else {
            // 获取目标实体
            entity = performanceHelp.getSetEntity(statisticsType,corpid,id);
            permissionList = performanceHelp.getPermissionList(entity);
            PerformanceSetExplainPojo explainPojo = performanceHelp.getPerformanceSetExplainPojo(entity);
            minCycle = explainPojo.getMinCycle();
            assessType = explainPojo.getAssessType();
            fixedValue = explainPojo.getFixedValue();
            Integer refType = XbbRefTypeEnum.UNKNOWN.getCode();
            if (entity.getRefTypes() != null) {
                List<Integer> refTypes = JsonHelperUtil.parseArray(entity.getRefTypes(), Integer.class);
                if (refTypes != null && refTypes.size() > 0) {
                    refType = refTypes.get(0);
                }
            }
            // 涉及到产品目标考核的时候允许选择考核的产品（多选）
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(refType);
            productFlag = xbbRefTypeEnum == XbbRefTypeEnum.PRODUCT;
            List<Long> assessProductList = explainPojo.getAccessProductIds();
            // 考核产品，且选择了考核哪些产品
            assessProductArray = getAssessProductArray(corpid, productFlag, assessProductList);
            handleProduct(entity,explainPojo,corpid,productFlag,assessProductList,assessProductArray);
            if (Objects.equals(statisticsType,StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())){
                driverSources = entity.getDriverSources();
                sourceAttr = entity.getSourceAttr();
                belongAttr = entity.getBelongAttr();
                timeAttr = entity.getTimeAttr();
                filter = entity.getFilter();
                penetrateAttr = entity.getPenetrateAttr();
            }
        }

        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getByCode(statisticsType);
        String statisticsTypeStr = statisticsTypeEnum.getName();
        Integer enable = entity.getEnable();
        String enableStr = (null == enable || (enable == 1)) ? "启用" : "不启用";
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 超管角色查看所有
        boolean containsFlag = true;
        // 获取操作人权限
        if (!DataPermissionEnum.ALL.getCode().equals(dataPermission)) {
            // 非超管，判断是否在考核对象内
            containsFlag = performanceHelp.checkViewPerformanceSetByUserId(corpid, userId, permissionList, id);
        }

        editVO.setId(id);
        editVO.setEnable(enable);
        editVO.setEnableStr(enableStr);
        editVO.setStatisticsType(statisticsType);
        editVO.setStatisticsTypeStr(statisticsTypeStr);
        editVO.setName(entity.getName());
        editVO.setMemo(entity.getMemo());
        editVO.setPermissions(permissionList);
        editVO.setMinCycle(minCycle);
        editVO.setMinCycleArray(minCycleArray);
        editVO.setAssessType(assessType);
        editVO.setFixedValue(fixedValue);
        editVO.setUnit(entity.getOriginalUnit());
        editVO.setUnitValue(performanceHelp.setUnit(entity));
        editVO.setAssessProductArray(assessProductArray);
        editVO.setProductFlag(productFlag);
        editVO.setDriverSources(driverSources);
        editVO.setSourceAttr(sourceAttr);
        editVO.setBelongAttr(belongAttr);
        editVO.setTimeAttr(timeAttr);
        editVO.setStatisticsWay(entity.getStatisticsWay());
        editVO.setFilter(filter);
        editVO.setPenetrateAttr(penetrateAttr);
        editVO.setContainsFlag(containsFlag);
        // 导入权限
        Set<String> perAlias = performanceSetEditDTO.getLoginUser().getPermSet();
        editVO.setImportFlag(perAlias.contains(ProPermissionAliasEnum.OBJECTIVE_IMPORT.getAlias()));

        return editVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PerformanceSetSaveVO save(PerformanceSetSaveDTO performanceSetSaveDTO) throws XbbException {
        PerformanceSetSaveVO saveVO = new PerformanceSetSaveVO();

        String corpid = performanceSetSaveDTO.getCorpid();
        Long id = performanceSetSaveDTO.getId();
        String name = performanceSetSaveDTO.getName();
        List<IdNamePojo> permissions = performanceSetSaveDTO.getPermissions();
        Integer minCycle = performanceSetSaveDTO.getMinCycle();
        Integer assessType = performanceSetSaveDTO.getAssessType();
        Double fixedValue = performanceSetSaveDTO.getFixedValue();
        List<Long> assessProduct = performanceSetSaveDTO.getAssessProduct();
        String unitValue = performanceSetSaveDTO.getUnitValue();
        Integer statisticsType = performanceSetSaveDTO.getStatisticsType();
        if (null == statisticsType || !StatisticsTypeEnum.getStatisticTypes().contains(statisticsType)) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240030,PerformanceErrorCodeEnum.API_ERROR_240030.getMsg());
        }

        //记录日志时，需要判断操作类型
        boolean isAdd = true;
        ChartEntity oldEntity = new ChartEntity();

        ChartEntity entity = new ChartEntity();
        Integer chartType = Objects.equals(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode(),statisticsType) ? ChartTypeEnum.PERFORMANCE.getCode() : ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode();
        if (null != id){
            //记录操作类型为编辑操作
            isAdd = false;
            // 获取目标实体
            entity = performanceHelp.getSetEntity(statisticsType,corpid,id);
            //记录老的entity实体，只用来记录日志时判断变更的字段
            BeanUtil.copyProperties(entity,oldEntity);
        }

        List<IdNamePojo> oldPermissionList = performanceHelp.getPermissionList(entity);

        BeanUtil.copyProperties(performanceSetSaveDTO, entity);
        // permissions
        JSONObject permissionObj = setPerSetPermission(permissions);
        entity.setPermissions(permissionObj);
        // explians
        PerformanceSetExplainPojo explains = new PerformanceSetExplainPojo();
        explains.setFixedValue(fixedValue);
        explains.setMinCycle(minCycle);
        explains.setAssessType(assessType);
        explains.setAccessProductIds(assessProduct);
        if (StringUtil.isNotEmpty(unitValue)){
            explains.setUnitValue(unitValue);
        }
        String explainsStr = JSON.toJSONString(explains);
        JSONObject explianObj = JsonHelperUtil.parseObject(explainsStr);
        //在图表中心仪表盘等场景会对explain塞入其他信息，此处不能直接覆盖
        JSONObject  oldExplains = entity.getExplains();
        if (Objects.nonNull(oldExplains)) {
            oldExplains.putAll(explianObj);
            entity.setExplains(oldExplains);
        } else {
            entity.setExplains(explianObj);
        }

        if (id == null) {
            // 新增的默认开启
            entity.setEnable(BasicConstant.IS_USE);
            // 自定义的校验数量
            if (Objects.equals(statisticsType,StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())){
                // 判断是否超过系统套餐数量
                Integer status = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.CUSTOM_CHART_NUM, BasicConstant.ONE);
                if(!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())){
                    throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224031);
                }
                // 校验是否超过自定义目标指标数量限制
                HashMap param = new HashMap(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("del",DelEnum.NORMAL.getDel());
                param.put("corpid",corpid);
                param.put("chartType",ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode());
                int count = chartCustomModel.getEntitysCount(param);
                if (count >= PaasConstant.CUSTOM_PERFORMANCE_MAX_NUM){
                    throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240037,String.format(PerformanceErrorCodeEnum.API_ERROR_240037.getMsg(),String.valueOf(PaasConstant.CUSTOM_PERFORMANCE_MAX_NUM)));
                }
            }
        }

        // 名称排重，导入用名称匹配
        if (chartModel.checkRepeat(corpid, name, id, chartType,statisticsType)) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240014, String.format(PerformanceErrorCodeEnum.API_ERROR_240014.getMsg(), "同名指标", "重新编辑指标名称"));
        }
        //最小考核周期
        MinCycleEnum minCycleEnum = MinCycleEnum.getByCode(minCycle);
        if (minCycleEnum == null) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "最小考核周期"));
        }
        // 考核方式
        AssessTypeEnum assessTypeEnum = AssessTypeEnum.getByCode(assessType);
        if (assessTypeEnum == null) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "考核方式"));
        }
        // 当最小考核周期为天，默认考核方式为“固定数值型”
        if (minCycleEnum == MinCycleEnum.DAY && assessTypeEnum != AssessTypeEnum.FIXED) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240008, PerformanceErrorCodeEnum.API_ERROR_240008.getMsg());
        }
        if (assessTypeEnum == AssessTypeEnum.FIXED) {
            if (fixedValue == null) {
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240004, String.format(PerformanceErrorCodeEnum.API_ERROR_240004.getMsg(), "固定频率值"));
            } else if (fixedValue < 0) {
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240015, String.format(PerformanceErrorCodeEnum.API_ERROR_240015.getMsg(), "固定频率值", "固定频率值"));
            }
        }

        // TODO 系统指标不能修改统计方式
//        Integer statisticsType = entity.getStatisticsType();
//        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getJsonByCode(statisticsType);
//        Integer statisticsWay = entity.getStatisticsWay();
//        if (StatisticsTypeEnum.SYSTEM_STATISTIC == statisticsTypeEnum && statisticsWay != null && statisticsWay != 0) {
//            throw new XbbException(ErrorCodeEnum.API_ERROR_240007, String.format(ErrorCodeEnum.API_ERROR_240007.getMsg(), "更改统计方式"));
//        }


        entity.setCorpid(corpid);
        try {
            if (Objects.equals(statisticsType,StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())){
                chartModel.save(entity);
            }else {
                customSave4Performance(entity, oldEntity, performanceSetSaveDTO);
                // 新建/保存分类
            }
        } catch (XbbException e) {
            LOG.error("保存业绩目标指标失败", e);
            ErrorCodeEnum errorCodeEnum = ErrorCodeEnum.getByCode(e.getCode());
            if (null != errorCodeEnum){
                throw new XbbException(errorCodeEnum.getCode(), errorCodeEnum.getMsg());
            }else{
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240038, PerformanceErrorCodeEnum.API_ERROR_240038.getMsg());
            }
        }


        // 处理考核对象缓存如果新设置的
        if (!permissions.equals(oldPermissionList)) {
            // 缓存名
            String sessionName4Dep = performanceHelp.createJedisName4Set(RedisPrefixConstant.PERFORMANCE_PERMISSION_DEP_ID, id);
            String sessionName4User = performanceHelp.createJedisName4Set(RedisPrefixConstant.PERFORMANCE_PERMISSION_USER_ID, id);
            // 处理考核对象转为部门ids--缓存还没有的话，则无需置入

            String redisDepIdIn = paasRedisHelper.getValue(sessionName4Dep, corpid);
            List<Long> depIdIn = null;
            if (redisDepIdIn != null) {
                depIdIn = performanceHelp.getPermission2DepIdIn(corpid, id, permissions);
            }
            // 处理考核对象转为员工ids--缓存还没有的话，则无需置入
            String redisUserIdIn = paasRedisHelper.getValue(sessionName4User, corpid);
            List<String> userIdIn = JsonHelperUtil.parseArray(redisUserIdIn, String.class);
            if (userIdIn != null) {
                Set<String> userIdSet = new HashSet<>(userIdIn);
                // 如果缓存已经存在，则把新设置的更新入缓存
                if (depIdIn != null) {
                    // 包含离职员工
                    userIdSet.addAll(userModel.getDepUserIdList4Visible(corpid, depIdIn, 1));
                    userIdSet.add("-1");
                    // 置入缓存
                    paasRedisHelper.setValue(sessionName4User, corpid, userIdSet, RedisTimeConstant.HOUR_DURATION);
                } else {
                    performanceHelp.getPermission2UserIdInFromJedis(corpid, permissions, id);
                }
            }
        }
        saveVO.setId(entity.getId());

        // 日志
        OperateTypeEnum addOrSet;
        String entityName;
        List<DetailLogPojo> detailArr;
        if(isAdd){
            //新增
            addOrSet = OperateTypeEnum.NEW;
            entityName = entity.getName();
            //新增不记录详情
            detailArr = null;
        }else{
            //编辑
            addOrSet = OperateTypeEnum.SET;
            entityName = oldEntity.getName();
            JSONObject oldAttr = performanceHelp.copyProperties(oldEntity,new PerformanceChartLogOrderPojo());
            JSONObject newAttr = performanceHelp.copyProperties(entity,new PerformanceChartLogOrderPojo());
            detailArr = logHelp.detailLog4PerformanceOfEdit(corpid,oldAttr,newAttr);
        }
        String opUserName = performanceSetSaveDTO.getLoginUserName();
        String opMemo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PERFORMANCE_CURRENCY),opUserName,addOrSet.getName(),entityName);
        mongoLogHelp.buildLog4DetailArr(detailArr,corpid, performanceSetSaveDTO.getUserId(), opUserName, OperateModuleTypeEnum.PerformanceObject, addOrSet, entity.getId().toString(), OtherSetEnum.GOAL_MANAGEMENT.getName(), opMemo, performanceSetSaveDTO.getHttpHeader());

        return saveVO;
    }

    /**
     * 目标管理自定义指标保存
     * @param chartEntity
     * @param oldEntity
     * @param baseDTO
     * @return com.xbongbong.pro.statistic.pojo.vo.ChartCustomSaveVO
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/4/27 10:15
     * @version 1.0
     */
    private Long customSave4Performance(ChartEntity chartEntity, ChartEntity oldEntity, BaseDTO baseDTO) throws XbbException {
        Long id = chartEntity.getId();
        String name = chartEntity.getName();
        String corpid = chartEntity.getCorpid();
        chartEntity.setChartType(ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode());
        chartEntity.setShowTypes(new JSONArray(Arrays.asList(ChartTypeEnum.PK_CUSTOM.getCode())));
        chartEntity.setPublish(BasicConstant.ZERO);
        chartEntity.setEnable(BasicConstant.ONE);
        if (id != null && id > 0) {
            /* 编辑 */
            // 自定义目标需要更新图表名称
            //直接使用旧图表即可，因为期category在此处不会变化
            ChartCategoryDTO chartCategoryDTO = new ChartCategoryDTO(oldEntity);
            //只查type是自定义目标类型的分类，因为改目标名称或开关时，只把它所属的自定义目标类型分类同步更改即可，不用全部，否则会把其他选择了该自定义目标的仪表盘也给更新（见bug：49406 内描述“名称自己改了”“名称都改了”）
            chartCategoryDTO.setTypeIn(Arrays.asList(ChartCategoryTypeEnum.PERFORMANCE_CUSTOM.getCode()));
            // 查分类
            List<ChartCategoryEntity> categoryEntityList = pkSetService.getAllCategoryList(chartCategoryDTO);
            // 把分类名的开启状态同步一下，编辑后默认开启
            categoryEntityList.forEach(i -> {
                i.setName(name);
                i.setNameEn(name);
                i.setEnable(BasicConstant.IS_USE);
            });
            chartCategoryModel.updateBatch(categoryEntityList, corpid);
            // 更新图表
            id = Long.valueOf(chartCustomModel.save(chartEntity));
        } else {
            /* 新建 */
            // 判断是否超过套餐数量
            Integer status = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.CUSTOM_CHART_NUM, BasicConstant.ONE);
            if(!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())){
                throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224031);
            }
            // 保存图表分类
            ChartCategorySaveDTO chartCategorySaveDTO = new ChartCategorySaveDTO();
            BeanUtil.copyProperties(baseDTO, chartCategorySaveDTO);
            Long categoryId4PerformanceChart = getCateoryId4Alias(corpid, ChartCategoryEnum.PERFORMANCE_FINISH_CHART.getAlias(), ChartCategoryTypeEnum.PERFORMANCE.getCode());
            chartCategorySaveDTO.setParentId(categoryId4PerformanceChart);
            chartCategorySaveDTO.setName(name);
            chartCategorySaveDTO.setNameEn(name);
            chartCategorySaveDTO.setId(chartEntity.getId());
            chartEntity.setCreatorId(baseDTO.getUserId());

            // feign调用获取所有分类
            XbbResponse<ChartCategorySaveVO> xbbResponse = chartCategoryFeignClient.chartCategorySave(chartCategorySaveDTO,LocaleContextHolder.getLocale().toString());
            if (!xbbResponse.isSuccess()) {
                ErrorCodeEnum errorCodeEnum = ErrorCodeEnum.getByCode(xbbResponse.getCode());
                if (null != errorCodeEnum){
                    throw new XbbException(errorCodeEnum.getCode(), errorCodeEnum.getMsg());
                }
            }
            // 反序列化
            ChartCategorySaveVO chartCategorySaveVO = xbbResponse.getResult();
            // 获取分类id
            Long categoryId = getCateoryId4Alias(corpid, ChartCategoryEnum.PERFORMANCE.getAlias(), ChartCategoryTypeEnum.WEB_INDEX_LEFT.getCode());
            chartEntity.setCategoryId2Category(categoryId);
            // 图表分类的id也保存，回显用
            chartEntity.setCategory(chartEntity.getCategory().fluentAdd(chartCategorySaveVO.getId()));
            // 保存指标、图表
            id = Long.valueOf(chartCustomModel.save(chartEntity));
        }
        return id;
    }

    /**
     * 获取指标的分类id
     * @param corpid
     * @param alias
     * @return
     * @throws XbbException
     */
    private Long getCateoryId4Alias(String corpid, String alias, int type) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("type", type);
        param.put("alias", alias);
        param.put("del",0);
        List<ChartCategoryEntity> categoryList = chartCategoryModel.findEntitys(param);
        Long categoryId ;
        if(CollectionsUtil.isNotEmpty(categoryList)){
            categoryId = categoryList.get(0).getId();
        } else {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224018);
        }
        return categoryId;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PerformanceSetDeleteVO delete(PerformanceSetDeleteDTO performanceSetDeleteDTO) throws XbbException {
        PerformanceSetDeleteVO deleteVO = new PerformanceSetDeleteVO();

        String corpid = performanceSetDeleteDTO.getCorpid();
        Long id = performanceSetDeleteDTO.getId();
        Integer statisticsType = performanceSetDeleteDTO.getStatisticsType();
        // 校验传过来的id是否能查到entity
        // 获取目标实体
        ChartEntity entity = performanceHelp.getSetEntity(statisticsType,corpid,id);
        entity.setDel(1);
        entity.setUpdateTime((long) DateUtil.getInt());
        try {
            if (Objects.equals(statisticsType,StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())){
                chartModel.update(entity);
            }else if(Objects.equals(statisticsType,StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())){
                chartCustomModel.update(entity);
                // 自定义pk把分类也删了
                ChartCategoryDTO chartCategoryDTO = new ChartCategoryDTO(entity);
                //此时 如果不限制自定义目标类型分类，会把其他选择了该自定义目标的仪表盘一并删除
                chartCategoryDTO.setTypeIn(Arrays.asList(ChartCategoryTypeEnum.PERFORMANCE_CUSTOM.getCode()));
                List<ChartCategoryEntity> categoryEntityList = pkSetService.getAllCategoryList(chartCategoryDTO);
                if (CollectionUtils.isNotEmpty(categoryEntityList)){
                    categoryEntityList.forEach(i -> i.setDel(DelEnum.DELETE.getDel()));
                    chartCategoryModel.updateBatch(categoryEntityList, corpid);
                }
            }
        } catch (Exception e) {
            LOG.error("删除业绩目标指标失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String opUserName = performanceSetDeleteDTO.getLoginUserName();
        String opMemo = opUserName + "删除了：“" + entity.getName() + "”指标";
        mongoLogHelp.buildLog(corpid, performanceSetDeleteDTO.getUserId(), opUserName, OperateModuleTypeEnum.PerformanceObject, OperateTypeEnum.DELETE, entity.getId().toString(), OtherSetEnum.GOAL_MANAGEMENT.getName(), opMemo, performanceSetDeleteDTO.getHttpHeader());

        return deleteVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PerformanceSetEnableVO enable(PerformanceSetEnableDTO performanceSetEnableDTO) throws XbbException {
        PerformanceSetEnableVO enableVO = new PerformanceSetEnableVO();

        String corpid = performanceSetEnableDTO.getCorpid();
        Integer statisticsType = performanceSetEnableDTO.getStatisticsType();
        Long id = performanceSetEnableDTO.getId();
        // 校验传过来的id是否能查到entity
        ChartEntity chartEntity = performanceHelp.getSetEntity(statisticsType,corpid,id);

        // update
        chartEntity.setEnable(performanceSetEnableDTO.getEnable());
        chartEntity.setUpdateTime((long) DateUtil.getInt());
        try {
            if (Objects.equals(statisticsType,StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())){
                chartModel.update(chartEntity);
            }else if(Objects.equals(statisticsType,StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())){
                chartCustomModel.update(chartEntity);
            }
            // 设置分类开启/关闭
            pkSetService.setCategoryEnable(performanceSetEnableDTO, chartEntity);
        } catch (Exception e) {
            LOG.error("启用/关闭业绩目标指标出错", e);
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240039, PerformanceErrorCodeEnum.API_ERROR_240039.getMsg());
        }

        // 日志
        String opUserName = performanceSetEnableDTO.getLoginUserName();
        String operationName;
        OperateTypeEnum operateTypeEnum;
        if(EnableEnum.OPEN.getCode().equals(performanceSetEnableDTO.getEnable())){
            operationName = EnableEnum.OPEN.getMemo();
            operateTypeEnum = OperateTypeEnum.ENABLE;
        }else{
            operationName = EnableEnum.CLOSE.getMemo();
            operateTypeEnum = OperateTypeEnum.CLOSE;
        }
        String opMemo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PERFORMANCE_CURRENCY),opUserName,operationName,chartEntity.getName());
        mongoLogHelp.buildLog(corpid, performanceSetEnableDTO.getUserId(), opUserName, OperateModuleTypeEnum.PerformanceObject, operateTypeEnum, "", OtherSetEnum.GOAL_MANAGEMENT.getName(), opMemo, performanceSetEnableDTO.getHttpHeader());

        return enableVO;
    }


    @Override
    public PerformanceSetCheckVO check(PerformanceSetCheckDTO performanceSetCheckDTO) throws XbbException {
        PerformanceSetCheckVO checkVO = new PerformanceSetCheckVO();
        checkVO.setFlag(false);
        try {
            List list = chartModel.getList(performanceSetCheckDTO.getCorpid(), null, ChartTypeEnum.PERFORMANCE.getCode());
            if (list != null && list.size() > 0) {
                checkVO.setFlag(true);
            }
        } catch (Exception e) {
            LOG.error("获取业绩目标指标失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return checkVO;
    }

    @Override
    public PerformanceSetListByPermissionVO listByPermission(PerformanceSetListByPermissionDTO performanceSetListByPermissionDTO) throws XbbException {
        PerformanceSetListByPermissionVO listByPermissionVO = new PerformanceSetListByPermissionVO();
        String platform = performanceSetListByPermissionDTO.getPlatform();
        String corpid = performanceSetListByPermissionDTO.getCorpid();
        String userId = performanceSetListByPermissionDTO.getUserId();
        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getByCode(performanceSetListByPermissionDTO.getStatisticsType());
        if(StatisticsTypeEnum.UNKNOWN.equals(statisticsTypeEnum)){
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240030,PerformanceErrorCodeEnum.API_ERROR_240030.getMsg());
        }
        //套餐
        if(!performanceHelp.filterPackagePermissions(corpid,statisticsTypeEnum)){
            return listByPermissionVO;
        }

        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
        }

        String checkedUserId = performanceSetListByPermissionDTO.getCheckedUserId();
        String checkedDepIdStr = performanceSetListByPermissionDTO.getCheckedDepId();
        Long checkedDepId = null;
        CompanyStructTypeEnum companyStructTypeEnum = CompanyStructTypeEnum.UNKNOWN;

        // 移动端：参数判断
        if (StringConstant.PLATFORM_DINGTALK.equals(platform)) {
            Integer companyStructType = performanceSetListByPermissionDTO.getCompanyStructType();
            companyStructTypeEnum = CompanyStructTypeEnum.getByCode(companyStructType);

            if (companyStructTypeEnum == CompanyStructTypeEnum.UNKNOWN) {
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "业绩类型"));
            }
            if (CompanyStructTypeEnum.USER == companyStructTypeEnum) {
                if (StringUtil.isEmpty(checkedUserId)) {
                    throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "员工"));
                }
            } else if (CompanyStructTypeEnum.DEPARTMENT == companyStructTypeEnum) {
                if (checkedDepIdStr == null || checkedDepIdStr.equals(BasicConstant.ZERO.toString())) {
                    throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "部门"));
                }
                try {
                    checkedDepId = Long.parseLong(checkedDepIdStr);
                } catch (NumberFormatException e) {
                    checkedDepId = null;
                }
                if (Objects.isNull(checkedDepId)) {
                    throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "部门"));
                }
            } else {
                throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "正确的业绩类型"));
            }
        }

        //获取 系统/自定义 图表列表
        List<ChartEntity> list;
        if(StatisticsTypeEnum.SYSTEM_STATISTIC.equals(statisticsTypeEnum)){
            //获取系统指标图表
            list = performanceHelp.getViewList(userEntity);
        }else{
            //获取自定义指标图表
            list = chartCustomModel.getList(corpid, EnableEnum.OPEN.getCode(),ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode());
        }

        if (StringConstant.PLATFORM_DINGTALK.equals(platform)) {
            List<ChartEntity> chartList = new ArrayList<>();
            for (ChartEntity chartEntity : list) {
                List<IdNamePojo> permissionList = performanceHelp.getPermissionList(chartEntity);
                Long setId = chartEntity.getId();

                // 判断选择的员工/部门是否在该指标的考核对象内
                if (CompanyStructTypeEnum.USER == companyStructTypeEnum
                        && !performanceHelp.checkViewPerformanceSetByUserId(userEntity.getCorpid(), checkedUserId, permissionList, setId)) {
                    continue;
                } else if (CompanyStructTypeEnum.DEPARTMENT == companyStructTypeEnum
                        && !performanceHelp.checkViewPerformanceSetByDeptId(userEntity.getCorpid(), checkedDepId, permissionList, setId)) {
                    continue;
                }
                chartList.add(chartEntity);
            }
            list.clear();
            list.addAll(chartList);
        }
        List<PerformanceSetListPojo> pojoList = new ArrayList<>();
        for (ChartEntity entity : list) {

            PerformanceSetExplainPojo explainPojo = performanceHelp.getPerformanceSetExplainPojo(entity);
            List<IdNamePojo> permissionList = performanceHelp.getPermissionList(entity);
            String depNames = performanceHelp.getPermissions2DepNames(permissionList);

            PerformanceSetListPojo pojo = new PerformanceSetListPojo();
            BeanUtil.copyProperties(entity, pojo);
            pojo.setDepNames(depNames);
            pojo.setAssessType(explainPojo.getAssessType());
            pojo.setMinCycle(explainPojo.getMinCycle());
            pojo.setUnit(performanceHelp.setUnit(entity));
            pojoList.add(pojo);
        }
        listByPermissionVO.setList(pojoList);

        return listByPermissionVO;
    }

    @Override
    public PerformanceSetPermissionListVO permissionList(PerformanceSetPermissionListDTO performanceSetPermissionListDTO) throws XbbException {
        PerformanceSetPermissionListVO permissionListVO = new PerformanceSetPermissionListVO();
        String corpid = performanceSetPermissionListDTO.getCorpid();
        String userId = performanceSetPermissionListDTO.getUserId();
        Long setId = performanceSetPermissionListDTO.getSetId();
        Integer statisticsType = performanceSetPermissionListDTO.getStatisticsType();
        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getByCode(performanceSetPermissionListDTO.getStatisticsType());
        if(StatisticsTypeEnum.UNKNOWN.equals(statisticsTypeEnum)){
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240001, PerformanceErrorCodeEnum.API_ERROR_240001.getMsg());
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        ChartEntity  chartEntity = performanceHelp.getSetEntity(statisticsType,corpid,setId);
        // 业绩类型：1员工的业绩 2部门的业绩
        CompanyStructTypeEnum companyStructTypeEnum = CompanyStructTypeEnum.getByCode(performanceSetPermissionListDTO.getCompanyStructType());
        if (companyStructTypeEnum == CompanyStructTypeEnum.UNKNOWN) {
            throw new XbbException(PerformanceErrorCodeEnum.API_ERROR_240006, String.format(PerformanceErrorCodeEnum.API_ERROR_240006.getMsg(), "业绩类型"));
        }

        List<IdNamePojo> permissionList = performanceHelp.getPermissionList(chartEntity);

        JSONArray list;
        if (companyStructTypeEnum == CompanyStructTypeEnum.USER) {
            // 考核员工（包含员工姓名、员工所在部门名等信息）
            list = getPermissionUserArray(userEntity, setId, permissionList);
        } else {
            // 考核部门ids
            List<Long> depIdIn = this.getPermission2DepIdsRetainSub(userEntity, setId, permissionList);
            list = new JSONArray();
            list.addAll(depIdIn);
        }

        permissionListVO.setList(list);

        return permissionListVO;
    }

    /****************************  共用方法  ************************************/
    @Override
    public Set<String> getPermission2UserIdsRetainSub(UserEntity userEntity, Long setId, List<IdNamePojo> permissionList,
                                                      Map<Long, String> nameDepMap) {
        Set<String> userIdIn = performanceHelp.getPermission2UserIdIn(userEntity.getCorpid(), setId, permissionList, nameDepMap);
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 非超管，则排除非自己下属的
        if (!DataPermissionEnum.ALL.getCode().equals(dataPermission)) {
            // 选择员工，将其下属和其取交集
            List<String> subIdList = userModel.getPkUserIdIn(userEntity, true, dataPermission);
            userIdIn.retainAll(subIdList);
            userIdIn.add("-1");
        }
        return userIdIn;
    }

    @Override
    public List<Long> getPermission2DepIdsRetainSub(UserEntity userEntity, Long setId, List<IdNamePojo> permissionList) {
        String corpid = userEntity.getCorpid();
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 获取考核对象内的部门ids（包含子部门）
        List<Long> depIdIn = performanceHelp.getPermission2DepIdIn(corpid, setId, permissionList);
        if (!DataPermissionEnum.ALL.getCode().equals(dataPermission)) {
            /*
             * 超管角色，看到所有考核的部门id列表
             * 非超管，则要与自己主管的部门ids取交集
             */
            // 获取自己主管的部门
            Set<Long> depIdSet = new HashSet<>(userModel.getUserManageDeptIdList(userEntity, true));
            // 获取主管的部门的子部门
            depIdSet.addAll(departmentModel.getSubDepIdList(corpid, depIdSet));
            // 考核对象与所属/下属部门取交集
            depIdIn.retainAll(depIdSet);
        }
        depIdIn.add(-1L);
        Set<Long> depIdSet = new HashSet<>(depIdIn);
        return new ArrayList<>(depIdSet);
    }

    @Override
    public String getDepNames4User(Map<Long, String> nameDepMap, UserEntity entity) {
        // 处理员工所在部门
        List<Long> depIdArray = JSONArray.parseArray(entity.getDepartment(), Long.class);
        StringBuffer depName = new StringBuffer();
        if(depIdArray != null) {
            for (Long depId : depIdArray) {
                String name = nameDepMap.get(depId);
                if (name == null) {
                    continue;
                }
                if (depName.length() != 0) {
                    depName.append(",");
                }
                depName.append(name);
            }
        }
        return depName.toString();
    }

    @Override
    public PerformanceSetPermissionListVO productList(PerformanceSetProductListDTO performanceSetProductListDTO) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",performanceSetProductListDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(),Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(boolQuery().mustNot(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID),0)));
        if (!Objects.isNull(performanceSetProductListDTO.getNameLike()) && !performanceSetProductListDTO.getNameLike().isEmpty()){
            boolQueryBuilder.should(matchPhraseQuery(ProductEnum.getAttrConnectData(ProductEnum.NAME), performanceSetProductListDTO.getNameLike()));
            boolQueryBuilder.should(matchPhraseQuery(ProductEnum.getAttrConnectData(ProductEnum.PRODUCT_NO), performanceSetProductListDTO.getNameLike()));
            boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
//        EsUtil.setNameLike(SaasMarkEnum.SAAS.getCode(),performanceSetProductListDTO.getNameLike(),IndexTypeEnum.IDX_SAAS_PRODUCT.getCode(),false,boolQueryBuilder);
        sourceBuilder.query(boolQueryBuilder);
        Integer page = performanceSetProductListDTO.getPage();
        Integer pageSize = performanceSetProductListDTO.getPageSize();
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest,PaasFormDataEntityExt.class);
        JSONArray productArray = new JSONArray();
        for (PaasFormDataEntityExt entityExt : esEntities.getContent()){
            JSONObject data = entityExt.getData();
            JSONObject productObj = new JSONObject();
            String name = data.getString(ProductEnum.NAME.getAttr());
            StringBuilder stringBuilder = new StringBuilder();
            if (Objects.equals(data.getString(ProductEnum.SPECIFICATION.getAttr()),"1")){
                JSONObject specifition = data.getJSONObject(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                if (!Objects.isNull(specifition)){
                    for (Map.Entry entry : specifition.entrySet()){
                        StringUtil.stringBuilderAppendSuffix(stringBuilder,"/",entry.getValue());
                    }
                }
            }else {
                String specifition =  data.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                stringBuilder.append(specifition);
            }
            StringBuilder specificationBuilder = new StringBuilder();
            if (stringBuilder.toString().isEmpty()){
                specificationBuilder.append(name);
            }else {
                specificationBuilder.append(name).append("(").append(stringBuilder).append(")");
            }

            productObj.put("name",specificationBuilder.toString());
            productObj.put("id",entityExt.getId());
            productArray.add(productObj);
        }
        PerformanceSetPermissionListVO performanceSetPermissionListVO = new PerformanceSetPermissionListVO();
        performanceSetPermissionListVO.setList(productArray);
        return performanceSetPermissionListVO;
    }

    @Override
    public Set<String> getPermission2UserIdsRetainSub(UserEntity userEntity) {
        Set<String> userIdIn = new HashSet<>(userModel.getSubIdListByDataPermission4Visible(DataPermissionEnum.ALL.getCode(), PaasConstant.SYS_USER_ID, userEntity.getCorpid(), 1, true));
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 非超管，则排除非自己下属的
        if (!DataPermissionEnum.ALL.getCode().equals(dataPermission)) {
            // 选择员工，将其下属和其取交集
            List<String> subIdList = userModel.getPkUserIdIn(userEntity, true, dataPermission);
            userIdIn.retainAll(subIdList);
            userIdIn.add("-1");
        }
        return userIdIn;
    }

    /**
     * 获取默认业绩目标指标
     *
     * @param chartType 报表类型枚举(16为业绩目标）
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-01-30 15:26
     * @version v1.0
     * @since v1.0
     */
    private List<ChartEntity> getDefaultSystemList(Integer chartType) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", "0");
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("chartType", chartType);
        param.put("orderByStr", "sort desc, id asc");
        return chartModel.findEntitys(param);
    }



    /**
     * 考核产品列表
     *
     * @param corpid            公司id
     * @param productFlag       是否考核标识
     * @param assessProductList 考核的产品ids
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-01-31 16:32
     * @version v1.0
     * @since v1.0
     */
    private List<PerformanceSetProductPojo> getAssessProductArray(String corpid, Boolean productFlag, List<Long> assessProductList) {
        List<PerformanceSetProductPojo> assessProductArray = new ArrayList<>();
        // 不是考核产品指标，则无需处理
        if (!productFlag || assessProductList == null || assessProductList.size() == 0) {
        return assessProductArray;
        }

        //先查出考核的产品实体--以获取产品名称、父产品id
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        // 添加corpid,formId,del
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, assessProductList));
        List<String> fieldList = Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID, BasicConstant.SERIAL_NO, StringConstant.JSON_DATA);
        List<PaasFormDataEntityExt> productList;
        try {
            productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        } catch (XbbException e) {
            return assessProductArray;
        }

        //产品id--产品实体
        Map<Long, PaasFormDataEntityExt> idMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt productEntity : productList) {
            idMap.put(productEntity.getId(), productEntity);
        }
        for (Long productId : assessProductList) {
            PaasFormDataEntityExt productEntityExt = idMap.get(productId);

            String productNo = "";
            String name;
            String specification = "";
            if (productEntityExt == null) {
                name = "异常产品";
            }else {
                JSONObject dataList = productEntityExt.getData();
                productNo = productEntityExt.getSerialNo();
                name = dataList.getString(ProductEnum.NAME.getAttr());
                // 产品规格
                StringBuilder specificationAliaBuilder = new StringBuilder();
                JSONObject specObj;
                try {
                    // {"规格1":"32G","规格2":"全网通"}
                    specObj = JSON.parseObject(dataList.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                } catch (Exception e) {
                    specObj = new JSONObject();
                }
                if (Objects.nonNull(specObj)) {
                    Set<String> keySet = specObj.keySet();
                    for (String key : keySet) {
                        String value = specObj.getString(key);
                        specificationAliaBuilder.append(value).append("/");
                    }
                }
                specification = specificationAliaBuilder.toString();
                if (!StringUtil.isEmpty(specification)) {
                    specification = specification.substring(0, specification.length() - 1);
                }
            }
            PerformanceSetProductPojo pojo = new PerformanceSetProductPojo();
            pojo.setId(productId);
            pojo.setName(name);
            pojo.setProductNo(productNo);
            pojo.setSpecification(specification);
            assessProductArray.add(pojo);
        }
        return assessProductArray;
    }


    /**
     * 获取考核对象内所有的员工列表
     *
     * @param userEntity     登录员工
     * @param setId          指标实体
     * @param permissionList 指标考核对象
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-02-22 19:05
     * @version v1.0
     * @since v1.0
     */
    private JSONArray getPermissionUserArray(UserEntity userEntity, Long setId, List<IdNamePojo> permissionList) {
        JSONArray jsonArray = new JSONArray();
        // 部门id--部门名称
        Map<Long, String> nameDepMap = new HashMap<>(16);
        // 考核的员工id列表（已经与自己的下属员工取过交集）
        Set<String> userIdSet = this.getPermission2UserIdsRetainSub(userEntity, setId, permissionList, nameDepMap);
        if (userIdSet == null || userIdSet.size() == 0) {
            return jsonArray;
        }
        //先将离职人员过滤掉
        Set<String> afterFilterUserIds = userModel.filterOutDepartingUser(userIdSet, userEntity.getCorpid());
        List<String> userIdIn = new ArrayList<>(afterFilterUserIds);
        // 查询筛选完离职员工之后的员工
        List<UserEntity> userList = userModel.findEntitysByUserIds(userIdIn, userEntity.getCorpid());

        for (UserEntity entity : userList) {
            // 部门名称
            String depName = this.getDepNames4User(nameDepMap, entity);
            JSONObject jsonObject = new JSONObject();
            // 员工userId
            jsonObject.put("id", entity.getUserId());
            // 员工姓名
            String name = entity.getName();
            jsonObject.put("name", name);
            // 员工所在的部门名称
            jsonObject.put("depName", depName);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * 设置新考核对象格式
     * @param permissions 考核对象
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-21 14:01
     * @since v1.0
     * @version v1.0
     */
    private JSONObject setPerSetPermission(List<IdNamePojo> permissions) {
        JSONObject performanceObj = new JSONObject();
        JSONObject visibleObj = new JSONObject();
        visibleObj.put("type", 2);
        visibleObj.put("dep", permissions);
        visibleObj.put("role", new ArrayList<>());
        visibleObj.put("user", new ArrayList<>());
        performanceObj.put("visible", 1);
        performanceObj.put("visibleScopeEnable", 1);
        performanceObj.put("visibleScopeRule", visibleObj);
        return performanceObj;
    }

    /**
     * 处理产品返回的特殊值
     * @param entity
     * @param explainPojo
     * @param corpid
     * @param productFlag
     * @param assessProductList
     * @param assessProductArray
     */
    private void handleProduct(ChartEntity entity,PerformanceSetExplainPojo explainPojo,String corpid,Boolean productFlag,List<Long> assessProductList,List<PerformanceSetProductPojo> assessProductArray){
        Integer refType = XbbRefTypeEnum.UNKNOWN.getCode();
        if (entity.getRefTypes() != null) {
            List<Integer> refTypes = JsonHelperUtil.parseArray(entity.getRefTypes(), Integer.class);
            if (refTypes != null && refTypes.size() > 0) {
                refType = refTypes.get(0);
            }
        }
        /*
         * 涉及到产品目标考核的时候允许选择考核的产品（多选）
         */
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(refType);
        productFlag = xbbRefTypeEnum == XbbRefTypeEnum.PRODUCT;
        assessProductList = explainPojo.getAccessProductIds();
        // 考核产品，且选择了考核哪些产品
        assessProductArray = getAssessProductArray(corpid, productFlag, assessProductList);
    }
}
